package com.XDApp.xdbase.activitys;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.BaseApplication;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.ProgressHUD;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.view.CRToast;
import com.XDApp.xdbase.xinsilu.R;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class RegistThirdActivity extends BaseActivity implements OnClickListener {
	private final String TAG = "RegistThirdActivity";
	private ImageView iv_back;
	private TextView tv_title;
	private Button bt_goto;
	private EditText et_pwd, et_againpwd;
	private SharedPreferences sp;
	private BaseApplication application;
	private String phone;

	@Override
	protected void initViews() {
		setContentView(R.layout.activity_regist_third);
		application = BaseApplication.getApplication();
		sp = getSharedPreferences(MainActivity.class.getSimpleName(), MODE_PRIVATE);
		phone = getIntent().getStringExtra("phone");

		iv_back = (ImageView) findViewById(R.id.title_back);
		tv_title = (TextView) findViewById(R.id.title_text);
		bt_goto = (Button) findViewById(R.id.bt_registthird);
		et_pwd = (EditText) findViewById(R.id.et_pwd);
		et_againpwd = (EditText) findViewById(R.id.et_again_pwd);

	}

	@Override
	protected void initEvents() {
		bt_goto.setOnClickListener(this);
		bt_goto.setClickable(false);
		iv_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		tv_title.setText("快速注册");

		et_pwd.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				bt_goto.setBackgroundResource(R.drawable.bt_login_normal);
				bt_goto.setTextColor(Color.parseColor("#777777"));
				bt_goto.setClickable(false);
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(et_againpwd.getText().toString().trim())) {
					return;
				}
				if (TextUtils.isEmpty(et_pwd.getText().toString().trim())) {
					bt_goto.setBackgroundResource(R.drawable.bt_login_normal);
					bt_goto.setTextColor(Color.parseColor("#777777"));
					bt_goto.setClickable(false);
					return;
				}
				bt_goto.setBackgroundResource(R.drawable.bt_login_press);
				bt_goto.setTextColor(Color.WHITE);
				bt_goto.setClickable(true);
			}
		});

		et_againpwd.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				bt_goto.setBackgroundResource(R.drawable.bt_login_normal);
				bt_goto.setTextColor(Color.parseColor("#777777"));
				bt_goto.setClickable(false);
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(et_pwd.getText().toString().trim())) {
					return;
				}
				if (TextUtils.isEmpty(et_againpwd.getText().toString().trim())) {
					bt_goto.setBackgroundResource(R.drawable.bt_login_normal);
					bt_goto.setTextColor(Color.parseColor("#777777"));
					bt_goto.setClickable(false);
					return;
				}
				bt_goto.setBackgroundResource(R.drawable.bt_login_press);
				bt_goto.setTextColor(Color.WHITE);
				bt_goto.setClickable(true);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_registthird:// 下一步
			String pwd = et_pwd.getText().toString().trim();
			String againPwd = et_againpwd.getText().toString().trim();
			if (!pwd.equals(againPwd)) {
				CommonUtil.showToast(mContext, "两次输入的密码不一致,请重新输入");
				et_pwd.setText("");
				et_againpwd.setText("");
				return;
			}
			getData(phone, pwd);
			break;
		default:
			break;
		}
	}

	// TODO 访问网络获取数据
	private void getData(final String phone, String pwd) {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("phone", phone);
			params.put("password", md5(pwd));
			params.put("ostype", xdConfig.ANDRODID);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.MOBILEREGISTER, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					Log.e(TAG, content);
					// 判断返回数据是否正确
					if (null == content) {
						CommonUtil.showToast(mContext, "获取数据失败");
						return;
					}
					JSONObject obj = new JSONObject().parseObject(content);
					String data = obj.getString("data");
					String state = obj.getString("state");
					JSONObject obj1 = new JSONObject().parseObject(data);
					String isUserReg = obj1.getString("isUserReg");
					String userID = obj1.getString("userID");
					Log.e(TAG, isUserReg);

					if ("1".equals(state)) {
						CRToast.show(RegistThirdActivity.this, "注册成功!");
						Editor editor = sp.edit();
						editor.putString("userID", userID).commit();
						Intent intent = new Intent(RegistThirdActivity.this, LoginActivity.class);
						startActivity(intent);
						finish();
					} else {
						CRToast.show(RegistThirdActivity.this, "注册失败!");
						return;
					}

				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

}
